package fun.coding.leetcode;

public class RemoveElement {

	public static void main(String[] args) {
		RemoveElement ins = new RemoveElement();
		
		int[] test1 = {1};
		int elem1 = 1;
		System.out.println(ins.removeElement(test1, elem1));
		
		int[] test2 = {3, 3};
		int elem2 = 3;
		System.out.println(ins.removeElement(test2, elem2));
		

		int[] test3 = {2, 2, 3};
		int elem3 = 2;
		System.out.println(ins.removeElement(test3, elem3));
	}
	// Keep two pointers from begin and end
	public int removeElement(int[] A, int elem) {
		if (A == null || A.length == 0) return 0;
		
		int l = 0;
		int r = A.length - 1;
		
		while (l <= r) {
			while (l <= r && A[l] != elem) l++;
			
			while (r >= l && A[r] == elem) r--;
			
			if (l < r) {
				A[l] = A[r];
				A[r] = elem;
				l++;
				r--;
			}
		}
		
		return r + 1;
	}
	
	/* another good way to keep two pointer
	 * 1:    int removeElement(int A[], int n, int elem) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      int cur = 0;  
5:      for(int i =0; i< n; i++)  
6:      {  
7:        if(A[i] == elem)  
8:          continue;  
9:        A[cur]=A[i];  
10:        cur++;  
11:      }  
12:      return cur;  
13:    }  
	 */

}
